package com.gitee.srurl.core.factory.handle;

import com.gitee.srurl.core.annotation.Order;
import com.gitee.srurl.core.api.IDataStore;
import com.gitee.srurl.core.cache.record.ShortUrlCacheManager;
import com.gitee.srurl.core.config.ShortUrlConfig;
import com.gitee.srurl.core.dto.request.GenerateShortUrlDTO;
import com.gitee.srurl.core.event.EventBusHandle;
import com.gitee.srurl.core.event.bloom.BloomEventParams;
import com.gitee.srurl.core.factory.ShortUrlFactory;
import com.gitee.srurl.core.dto.DataModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author zxw
 * @date 2023/4/29 8:43
 */
@Component
@Order(4)
@Slf4j
public class DataStoreHandle implements IGenerateShortUrlHandle {

    @Autowired
    private ShortUrlCacheManager shortUrlCacheManager;

    @Override
    public boolean handle(GenerateShortUrlDTO generateShortUrlDTO) {

        ShortUrlConfig shortUrlConfig = ShortUrlFactory.getShortUrlConfig();
        IDataStore dataStore = shortUrlConfig.getDataStore();
        DataModel dataModel = DataModel.builder()
                .originUrl(generateShortUrlDTO.getOriginUrl())
                .shortKey(generateShortUrlDTO.getShortKey())
                .shortUrl(generateShortUrlDTO.getShortUrl())
                .domain(generateShortUrlDTO.getShortUrlDomain())
                .times(generateShortUrlDTO.getTimes())
                .expireTime(generateShortUrlDTO.getExpireTime())
                .build();

        // 保存之前发布布隆过滤器添加事件
        BloomEventParams bloomEventParams = new BloomEventParams();
        bloomEventParams.setShortId(generateShortUrlDTO.getShortKey());
        bloomEventParams.setOriginUrl(generateShortUrlDTO.getOriginUrl());
        bloomEventParams.setShortUrl(generateShortUrlDTO.getShortUrl());
        EventBusHandle.post(bloomEventParams);
        // 删除缓存
        shortUrlCacheManager.removeCache(generateShortUrlDTO.getShortKey());
        // 保存数据 保存后面的操作会在删除一遍缓存
        boolean save = dataStore.save(dataModel);
        if (!save) {
            log.error("短网址参数:{},存储失败", generateShortUrlDTO);
            generateShortUrlDTO.setMsg("短网址存储失败");
            generateShortUrlDTO.setSuccess(false);
            return false;
        }

        return true;
    }
}
